<template>
    <div class="inner_loadblance">
      <crud-component
        :columns="columns"
        :queryFields="queryFields"
        :formButtons="formButtons"
        :extraButtons="extraButtons"
        :actionButtons="actionButtons"
        :queryFieldsPerRow="queryFieldsPerRow"
        :getListData="getListData"
        :actionColumn="actionColumn"
        :total="total"
      ></crud-component>
    </div>
  </template>
  
  <script setup lang="ts">
  import { defineComponent, ref, onMounted, h } from "vue";
  import { ElMessage } from "element-plus";
  import CrudComponent from "@/components/curd/CrudComponent.vue";
  
//   import {
//     getAlgorithmDeploymentList,
//     getWorkloadYaml,
//   } from "@/api/LoadBalance/Index.ts";
  
  const columns = setupColumns();
  const queryFields = setupQueryFields();
  const clusterOptions = ref<any[]>([]);
  const formButtons = setupFormButtons(clusterOptions);
  const extraButtons = setupExtraButtons(openDeployDialog);
  const actionButtons = setupActionButtons(openDeployDialog, handleViewYaml);
  const actionColumn = setupActionColumn();
  const total = ref(0);
  const queryFieldsPerRow = 5;
  
  async function getListData(params: any) {
        try {
          const res = await getAlgorithmDeploymentList(params);
          if (res && res.dataList && typeof res.totalRecord === "number") {
            total.value = res.totalRecord;
            return { items: res.dataList, total: res.totalRecord };
          } else {
            throw new Error("接口返回的数据结构不正确");
          }
        } catch (error) {
          console.error("获取数据失败:", error);
          return { items: [], total: 0 };
        }
      }
  
  async function handleViewYaml(row: any) {
    try {
      const response = await getWorkloadYaml({
        namespace: row.namespace,
        kind: row.kind,
        name: row.name,
        clusterId: selectedClusterId.value, // 使用选中的集群ID
      });
      selectedYamlContent.value = response; // 使用 response.data
      yamlDialogVisible.value = true;
    } catch (error) {
      console.error("获取YAML内容失败:", error);
      ElMessage.error("获取YAML内容失败");
    }
  }
  
  async function openDeployDialog(row?: any) {
    if (row) {
      // 编辑模式
      // isEditMode.value = true;
      // const response = await getWorkloadYaml({
      //   namespace: row.namespace,
      //   kind: row.kind,
      //   name: row.name,
      //   clusterId: selectedClusterId.value, // 使用选中的集群ID
      // });
      // deployForm.value = {
      //   ...row,
      //   clusterId: selectedClusterId.value, // 使用选中的集群ID
      //   inputText: response, // 将YAML内容存储到inputText中
      // };
    } else {
      // 创建模式
      //     isEditMode.value = false;
      //     deployForm.value = {
      //       kind: "",
      //       clusterId: "",
      //       poolId: "",
      //       namespace: "",
      //       name: "",
      //       replicas: 1,
      //       inputText: "",
      //     };
      //   }
      //   deployDialogVisible.value = true;
    }
  }
  function setupColumns() {
    return ref([
      { prop: "name", label: "名称", width: 240 },
      { prop: "kind", label: "工作负载", width: 150 },
      {
        prop: "poolName",
        label: "资源池",
        width: 200,
        render: (row: any) => h("span", row.poolId || row.poolName || "无"),
      },
      { prop: "namespace", label: "命名空间", width: 150 },
      {
        prop: "labels",
        label: "标签",
        width: 300,
        className: "custom-labels-cell",
        render: (row: any) =>
          h(
            "div",
            Object.entries(row.labels).map(([key, value]) =>
              h(
                "div",
                {
                  style: {
                    border: "1px solid #eaeaea",
                    padding: "0 5px",
                    borderRadius: "4px",
                    marginTop: "3px",
                  },
                },
                `${key}: ${value}`
              )
            )
          ),
      },
      {
        prop: "imageName",
        label: "镜像",
        className: "custom-labels-cell",
        width: 200,
      },
      {
        prop: "containerCount",
        label: "容器组数量",
        width: 180,
        render: (row: any) =>
          h("span", `${row.readyReplicas || 0} / ${row.replicas || 0}`),
      },
      {
        prop: "createTime",
        label: "创建时间",
        render: (row: any) =>
          h("span", dayjs(row.createTime).format("YYYY-MM-DD HH:mm:ss")),
        width: 200,
      },
    ]);
  }
  
  function setupQueryFields() {
    return ref([
      {
        prop: "clusterId",
        label: "全部集群:",
        type: "el-select",
        attrs: { options: [] },
        defaultValue: "",
      },
      {
        prop: "namespace",
        label: "命名空间:",
        type: "el-select",
        attrs: { options: [] },
        defaultValue: "",
      },
      {
        prop: "kind",
        label: "工作负载:",
        type: "el-select",
        attrs: {
          placeholder: "请选择",
          options: [
            { label: "Deployment", value: "Deployment" },
            { label: "StatefulSet", value: "StatefulSet" },
          ],
        },
        defaultValue: "Deployment",
      },
    ]);
  }
  
  function setupFormButtons(clusterOptions: any) {
    return ref([
      { label: "查询", type: "primary", handler: () => {} },
      {
        label: "重置",
        handler: (queryForm: any) => {
          for (const key in queryForm) {
            queryForm[key] = "";
            if (key === "clusterId" && clusterOptions.value.length > 0) {
              queryForm[key] = clusterOptions.value[0].value;
            } else if (key === "kind") {
              queryForm[key] = "Deployment";
            }
          }
        },
      },
    ]);
  }
  
  function setupExtraButtons(openDeployDialog: () => void) {
    return ref([
      {
        label: "部署服务",
        type: "primary",
        handler: () => openDeployDialog(),
      },
    ]);
  }
  
  function setupActionButtons(
    openDeployDialog: (row: any) => void,
    handleViewYaml: (row: any) => void
  ) {
    return ref([
      { label: "编辑YAML", handler: openDeployDialog, type: "btn" },
      {
        label: "查看YAML",
        handler: handleViewYaml,
        type: "btn",
      },
    ]);
  }
  
  function setupActionColumn() {
    return { label: "操作", width: "350", fixed: "right" };
  }
  </script>
  
  <style scoped lang="scss"></style>
  